#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include "global.h"
#include "lw_oopc.h"
#include "textTexture.h"
#include "textButton.h"
#include "inputBox.h"
#define pc_build
#ifdef pc_build
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#else
#include "SDL.h"
#include "SDL_ttf.h"
#endif
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
int w = WINDOW_W, h = WINDOW_H; // 屏幕大小
#define SDL_DELAY 12
#define FRAMERATE 60

int success = 1;
SDL_Event e;
int gQuit = 0;
float mouseX = 0;
float mouseY = 0;
int fingerSupport = 1;

int numFrames = 0;
int startTime = 0;
SDL_Color fpsColor = {255, 0, 0, 255};

SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
SDL_bool full_screen = SDL_FALSE;
TTF_Font *font;
TextTexture *textTexture;

TextButton *registerButton;

InputBox *accountInput;
InputBox *pwdInput;

SDL_Color textMenuColor = {0, 0, 0, 255};
char *composition;
int cursor;
enum Page{regPage};
int selection_len;
int init()
{
    if (TTF_Init() == -1)
    {
        SDL_Log("TTF unable to initialize! Error: %s\n", TTF_GetError());
        success = 0;
    }
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0)
    {
        SDL_Log("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
        success = 0;
    }
    else
    {
#ifdef android_build
        window = SDL_CreateWindow("", 0, 0, 0, 0, 0);

#else
        window = SDL_CreateWindow("新三国", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_W, WINDOW_H, SDL_WINDOW_RESIZABLE);

#endif
        if (window == NULL)
        {
            SDL_Log("Window could not be created! SDL Error: %s\n", SDL_GetError());
            success = 0;
        }
        else
        {
            // Create renderer for window
            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
            if (renderer == NULL)
            {
                SDL_Log("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
                success = 0;
            }
        }
    }
    return success;
}
void waitSecondsTodo(void *argc)
{
    SDL_Delay(((int)argc) * 1000);
}
void drawFps()
{
    int elapsedMS = SDL_GetTicks() - startTime; // Time since start of loop
    ++numFrames;
    if (elapsedMS)
    {                                                // Skip this the first frame
        double elapsedSeconds = elapsedMS / 1000.0;  // Convert to seconds
        int fps = (int)(numFrames / elapsedSeconds); // FPS is Frames / Seconds
        char buf[20];
        sprintf(buf, "FPS:%d", fps);
        // printf("buf = %s\n", buf);
        textTexture->drawText(renderer, textTexture, font, buf, 200, 10, 1.0f, textTexture->defaultColor);
    }
}
void handleDown()
{
    float x = 0, y = 0;
    x = e.button.x;
    y = e.button.y;
    if (fingerSupport)
    {
        x = mouseX;
        y = mouseY;
    }
}
void interpolateFinger()
{
    SDL_Finger finger;
    SDL_FingerID index = e.tfinger.fingerId;
    finger.id = index;
    finger.x = e.tfinger.x;
    finger.y = e.tfinger.y;
    SDL_GetWindowSize(window, &w, &h);
    mouseX = (float)(w)*e.tfinger.x;
    mouseY = (float)(h)*e.tfinger.y;
    if (mouseX > 0)
    {
        fingerSupport = 1;
    }
}

void interpolateMouse()
{
    mouseX = (float)(w) / w * e.motion.x;
    mouseY = (float)(h) / h * e.motion.y;
}

void handleButtons()
{
    SDL_KeyCode mkey = e.key.keysym.sym;

    switch (e.type)
    {
    case SDL_QUIT:
        gQuit = 1;
        break;
    case SDL_KEYDOWN:
    {

        if (mkey == 'q')
        {
            gQuit = 1;
        }
        else if (mkey == SDLK_BACKSPACE)
        {
            // accountInput->text
            if (accountInput->editing == SDL_TRUE)
            {
                char buf[100];
                strcpy(buf, accountInput->text);
                if (strlen(buf) >= 1)
                {

                    buf[strlen(buf) - 1] = '\0';
                    printf("buf = %s\n", buf);
                    strcpy(accountInput->text, buf);
                }
                else
                {
                    strcpy(accountInput->text, "");
                }
            }
            if (pwdInput->editing == SDL_TRUE)
            {

                char buf2[100];
                strcpy(buf2, pwdInput->text);

                if (strlen(buf2) >= 1)
                {

                    buf2[strlen(buf2) - 1] = '\0';
                    strcpy(pwdInput->text, buf2);
                }
                else
                {
                    strcpy(pwdInput->text, "");
                }
            }
        }
    }
    break;
    case SDL_FINGERDOWN:
        interpolateFinger();
        handleDown();
        break;
    case SDL_MOUSEBUTTONDOWN:
        fingerSupport = 0;
        handleDown();
        interpolateMouse();
        if (SDL_PointInRect(&(SDL_Point){e.button.x, e.button.y}, &accountInput->rect))
        {
            accountInput->editing = SDL_TRUE;
        }
        else
        {
            accountInput->editing = SDL_FALSE;
        }

        interpolateMouse();
        if (SDL_PointInRect(&(SDL_Point){e.button.x, e.button.y}, &pwdInput->rect))
        {
            pwdInput->editing = SDL_TRUE;
        }
        else
        {
            pwdInput->editing = SDL_FALSE;
        }
     if (SDL_PointInRect(&(SDL_Point){e.button.x, e.button.y}, &registerButton->rect))
        {
            //register btn clicked
            printf("register btn clicked account=%s,pwd=%s",accountInput->text, pwdInput->text);
            //check
            if( strlen(accountInput->text) >5 && strlen(accountInput->text) <10 && strlen(pwdInput->text) >5 && strlen(pwdInput->text) <10){
                        printf("reg ok\n");
                        //goto next page
            }
                

        }
      

        break;
    case SDL_MOUSEMOTION:

        break;
    case SDL_MOUSEBUTTONUP:

        break;
    case SDL_TEXTINPUT:
        if (accountInput->editing)
        {
   
             SDL_SetTextInputRect(&accountInput->rect);
            if(strlen(accountInput->text) <= 16)
            strcat(accountInput->text, e.text.text);
        }
        if (pwdInput->editing)
        {
             if(strlen(pwdInput->text) <= 16)
            strcat(pwdInput->text, e.text.text);
        }
        break;
    case SDL_TEXTEDITING:

        composition = e.edit.text;
        cursor = e.edit.start;
        selection_len = e.edit.length;
        break;
    }
}

void tick()
{
    SDL_RenderClear(renderer);
    while (SDL_PollEvent(&e) != 0)
    {
        handleButtons();
    }

    SDL_SetRenderDrawColor(renderer, 117, 117, 117, 255);
    SDL_RenderClear(renderer);

    SDL_GetWindowSize(window, &w, &h);

    // drawFps();
    textTexture->drawText(renderer, textTexture, font, "注册", w / 2, 10, 1.0f, textTexture->defaultColor);
    registerButton->show(renderer, registerButton, font, textTexture);
    accountInput->show(renderer, accountInput, font, textTexture);
    pwdInput->show(renderer, pwdInput, font, textTexture);
    SDL_RenderPresent(renderer);
}
void loadMedia()
{
#if defined(pc_build) || defined(__EMSCRIPTEN__)
    font = TTF_OpenFont("assets/fzpix.ttf", FONT_SIZE);

#else
    font = TTF_OpenFont("fzpix.ttf", FONT_SIZE);

#endif
}
void quit()
{
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    TTF_Quit();
    lw_oopc_delete(textTexture);
    lw_oopc_delete(registerButton);
    lw_oopc_delete(accountInput);
    lw_oopc_delete(pwdInput);
    SDL_StopTextInput();

}
void gameInit()
{
    SDL_GetWindowSize(window, &w, &h);
    textTexture = TextTexture_new();
    textTexture->init(textTexture, "textTexture", "textTexture", SDL_TRUE);
    // const char *name,const char *text, SDL_Rect rect, SDL_bool enabled, SDL_KeyCode bindKey, SDL_Color color, SDL_Color textColor)
    registerButton = TextButton_new();
    registerButton->init(registerButton, "registerButton", "注册", (SDL_Rect){w / 2, h - MARGIN, FONT_SIZE * 3, FONT_SIZE * 2}, SDL_TRUE, 'r', (SDL_Color){255, 255, 255, 255}, textMenuColor);
    accountInput = InputBox_new();
    accountInput->init(accountInput, "account", "123456", (SDL_Rect){w / 2 - FONT_SIZE * 5, h / 2, FONT_SIZE * 10, FONT_SIZE * 2}, SDL_TRUE, (SDL_Color){255, 255, 255, 255}, textMenuColor);
    pwdInput = InputBox_new();
    pwdInput->init(pwdInput, "pwd", "123456", (SDL_Rect){w / 2 - FONT_SIZE * 5, h / 2 + MARGIN, FONT_SIZE * 10, FONT_SIZE * 2}, SDL_TRUE, (SDL_Color){255, 255, 255, 255}, textMenuColor);

    SDL_StartTextInput();
}
void loop()
{
    startTime = SDL_GetTicks();
#if __EMSCRIPTEN__
    emscripten_set_main_loop(tick, 0, 0);
#else
    while (!gQuit)
    {
        tick();
        long current = SDL_GetTicks();
        long cost = current - startTime;
        long frame = 1000 / FRAMERATE;
        long delay = frame - cost;
        if (delay > 0)
            SDL_Delay(delay);
    }
    quit();

#endif
}
#ifdef pc_build
#undef main
#endif
int main(int argc, char *argv[])
{
    if (!init())
    {
        SDL_Log("SDL could not be initialized\n");
        return 1;
    }
    gameInit();
    loadMedia();
    loop();
    return 0;
}
